import logging


class SimpleLogger:
    def __init__(self, log_file="app.log", level=logging.INFO):
        """
        初始化日志器
        :param log_file: 日志文件路径
        :param level: 日志级别
        """
        self.logger = logging.getLogger("SimpleLogger")
        self.logger.setLevel(level)

        # 防止重复添加 Handler
        if not self.logger.handlers:
            # 创建文件日志处理器
            file_handler = logging.FileHandler(log_file, encoding="utf-8")
            file_handler.setLevel(level)

            # 创建控制台日志处理器
            console_handler = logging.StreamHandler()
            console_handler.setLevel(level)

            # 定义日志格式
            formatter = logging.Formatter(
                "%(asctime)s - %(levelname)s - %(message)s",
                datefmt="%Y-%m-%d %H:%M:%S"
            )

            file_handler.setFormatter(formatter)
            console_handler.setFormatter(formatter)

            self.logger.addHandler(file_handler)
            self.logger.addHandler(console_handler)

    def log(self, level, *args):
        """
        记录日志，支持多个参数
        :param level: 日志级别（DEBUG, INFO, WARNING, ERROR, CRITICAL）
        :param args: 任意类型的日志信息
        """
        message = " ".join(map(str, args))
        if level == "DEBUG":
            self.logger.debug(message)
        elif level == "INFO":
            self.logger.info(message)
        elif level == "WARNING":
            self.logger.warning(message)
        elif level == "ERROR":
            self.logger.error(message)
        elif level == "CRITICAL":
            self.logger.critical(message)
        else:
            raise ValueError("Unsupported log level")

    def debug(self, *args):
        self.log("DEBUG", *args)

    def info(self, *args):
        self.log("INFO", *args)

    def warning(self, *args):
        self.log("WARNING", *args)

    def error(self, *args):
        self.log("ERROR", *args)

    def critical(self, *args):
        self.log("CRITICAL", *args)


# logging.basicConfig(level=logging.DEBUG, 
#                     format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 
#                     datefmt='%Y-%m-%d %H:%M:%S', 
#                     filename='./app.log', 
#                     filemode='w')

# logger = logging.getLogger(__name__)


# logger.debug("userToken req",rData,type(rData))会出现错误： TypeError: not all arguments converted during string formatting
logger = SimpleLogger(log_file="app.log", level=logging.DEBUG)
